<template>
    <view @tap="$page.open('/pages/city/city?event=x-city')">
        <text v-if="positionLoading">定位中...</text>
        <text v-else>{{ GLOBALSTATUS.city.title }}</text>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useMap } from "@/utils/map";
import { $page } from "@/utils";
import { $EventName } from "@/utils/const/env";
import { useStatusStore, useRefs } from "@/stores";
let map: any;
const positionLoading = ref(false);
const StatusStore = useStatusStore();
const { GLOBALSTATUS } = useRefs(StatusStore);
const useInitMap = () => {
    map = useMap(() => {
        nextTick(() => {
            getPosition();
        });
    });
}
onMounted(() => {
    useInitMap();
    uni.$once($EventName.WEBCONFIG_READY, useInitMap)
    uni.$on('x-city', (res) => {
        StatusStore.set('city', res)
        uni.$emit($EventName.X_CITY_CHANGE, res);
    })
})
onBeforeUnmount(() => {
    uni.$off('x-city');
	uni.$off($EventName.WEBCONFIG_READY,useInitMap);
})
const getPosition = () => {
    if (!map.isReady()) { return; }
    positionLoading.value = true;
    map.getCurrentPosition({isHighAccuracy:false}).then((result:any) => {
        // #ifdef H5
        getAddress([result.position.lng, result.position.lat]);
        StatusStore.set('location', {
            latitude: result.position.lat,
            longitude: result.position.lng
        });
        // #endif
        // #ifdef APP
        let title = result.address.province;
        if(result.address.city){
            title = result.address.city;
        }
        StatusStore.set('city', {
            title: title
        });
        StatusStore.set('location', {
            latitude: result.latitude,
            longitude: result.longitude
        });
        // #endif
        // #ifdef MP-WEIXIN
        let title = result.regeocodeData.addressComponent.province;
        if(result.regeocodeData.addressComponent.city.length>0){
            title = result.regeocodeData.addressComponent.city;
        }
        StatusStore.set('city', {
            title: title
        });
        StatusStore.set('location', {
            latitude: result.latitude,
            longitude: result.longitude
        });
        // #endif
    }).catch(() => {
    }).finally(() => {
        positionLoading.value = false;
    });
}
const getAddress = (lnglat:any) => {
    map.getAddress(lnglat).then((result:any) => {
        let title = result.addressComponent.province;
        if(result.addressComponent.city){
            title =result.addressComponent.city;
        }
        StatusStore.set('city', {
            title:title
        });
    }).catch((err:any) => {
        console.log(err);
    })
}
</script>

<style lang="scss" scoped></style>